var prefix = jsctx + "/member";
var premix = jsctx + "/ugsMemberPointRecord";


var member = (function () {
    $('#exampleTable').on('load-success.bs.table', function (e, data) {
        if (data.total && !data.rows.length) {
            $('#exampleTable').bootstrapTable('selectPage').bootstrapTable('refresh');
        }
    });

    function getCheckedRoles() {
        var rows = $("#exampleTable").bootstrapTable('getSelections');// 获得要删除的数据
        if (rows.length == 0) {// rows 主要是为了判断是否选中，下面的else内容才是主要
            return;
        } else {
            var ids = new Array();// 声明一个数组
            $(rows).each(function () {// 通过获得别选中的来进行遍历
                ids.push(this.memberId);// cid为获得到的整条数据中的一列
            });
            // $('#activityName').val(ids);
            parent.document.getElementById("userIds").value = ids;


        }

    }


    function reLoad() {
        $(".fixed-table-header-columns").css("display", "none");
        $(".fixed-table-body-columns").css("display", "none");
        $('#exampleTable').bootstrapTable('refresh');
    };

    function init() {
        setTimeout(function () {//防止先于-读取缓存执行
            load();
        }, 10)
    };
    var h = $(window).height() - 80;

    function load() {
        $('#exampleTable')
            .bootstrapTable({
                method: 'get',
                url: prefix + "/listMember",
                iconSize: 'outline',
                toolbar: '#exampleToolbar',
                striped: false,
                dataType: "json",
                pagination: true,
                singleSelect: false,
                pageList: [10, 20, 30],
                pageSize: 10,
                pageNumber: parseInt(cacheOffset),
                sidePagination: "server",
                cache: false,
                height: h,
                paginationShowPageGo: true,
                rightFixedColumns: false,
                showColumns: true,
                queryParams: function (params) {
                    return {
                        limit: params.limit,
                        offset: (params.offset / params.limit) + 1,
                        mobile: $("#mobile").val().trim(),
                        nickname: $("#nickname2").val().trim()
                    };
                },
                columns: [

                    {
                        checkbox: true, field: '', width: '50', align: 'left',

                    },
                    {
                        field: 'number',
                        title: '序号',
                        width: '50', align: 'center',
                        formatter: function (value, row, index) {
                            return index + 1;
                        }
                    },
                    {field: 'memberId', title: '用户ID', align: 'center', width: '80'},
                    {
                        field: 'nickname', title: '姓名', width: '100', align: 'center',
                        formatter: function (value, row, index) {
                            if (value == null || value == '0') {
                                return row.nickname2;
                            } else {
                                return value;
                            }
                        }
                    },
                    {field: 'recommenderId', title: '推荐人ID', width: '80', align: 'center'},
                    {
                        field: 'isMemberLevel', title: '用户类型', width: '100', align: 'center',
                        formatter: function (value, row, index) {
                            if (value == '0') {
                                return '非会员';
                            } else {
                                return '会员';
                            }
                        }
                    },
                    {field: 'mobile', title: '手机号', width: '100', align: 'center'},
                    {field: 'allRechargeAmount', title: '充值额度(元)', width: '50', align: 'center'},
                    {
                        field: 'giveAccount', title: '权益金(元)', width: '100', align: 'center',
                        formatter: function (value, row, index) {
                            return value + row.frozenGiveAccount;
                        }

                    },
                    {field: 'orderCount', title: '累计消费次数(次)', width: '50', align: 'center'},
                    {field: 'allOrderAmount', title: '累计消费金额(元)', width: '50', align: 'center'},
                    {
                        field: 'memberLevel', title: '会员等级', width: '100', align: 'center',
                        formatter: function (value, row, index) {
                            if (row.memberLevel != null && row.memberLevel != '') {
                                return row.memberLevel;
                            } else {
                                return '';
                            }
                        }
                    },
                    {
                        field: 'gain', title: '会员权益', width: '100', align: 'center'
                    },

                    {field: 'registerTime', title: '注册时间', width: '100', align: 'center'},
                    {field: 'lastLoginTime', title: '最近登陆时间', width: '100', align: 'center'},
                    {
                        field: 'status',
                        title: '状态',
                        width: '100', align: 'center',
                        formatter: status_switch/*function (value, row, index) {
                            if (row.status == '0') {
                                return "<input type='checkbox' id='member-status' name='member-status' value=" + row.memberId + " checked>";
                            } else if (row.status == '1') {
                                return "<input type='checkbox' id='member-status' name='member-status' value=" + row.memberId + " >";
                            }
                        }*/
                    },
                    {
                        title: '操作',
                        field: 'orderId',
                        width: '200', align: 'center',
                        class: '',
                        formatter: function (value, row, index) {
                            var d = '<a class="btn btn-success btn-sm ' + has_edit + '" href="#" title="详情" onclick="member.detailMember(\''
                                + row.memberId
                                + '\')">详情</a> ';
                            var a = '';
                            var b = '';
                            var c = '';
                            var e = '';
                            var f = '';
                            // if (MemberManager_member_look) {
                            //     d = '<a class="btn btn-success btn-sm ' + has_edit + '" href="#" title="详情" onclick="member.detailMember(\''
                            //         + row.memberId
                            //         + '\')">详情</a> ';
                            //     a = '<a class="btn btn-primary btn-sm ' + has_edit + '" href="#" title="余额变动记录" onclick="member.memberAccountRecord(\''
                            //         + row.memberId
                            //         + '\')">余额变动记录</a> ';
                            //     f = '<a class="btn btn-primary btn-sm ' + has_edit + '" href="#" title="积分变动记录" onclick="member.integralAccountRecord(\''
                            //         + row.memberId
                            //         + '\')">积分变动记录</a> ';
                            // }
                            // if (MemberManager_member_update) {
                            //     b = '<a class="btn btn-danger btn-sm ' + has_edit + '" href="#" title="充值" onclick="member.recharge(\''
                            //         + row.memberId
                            //         + '\')">充值</a> ';
                            //     if (row.status == '0') {
                            //         c = '<a class="btn btn-danger btn-sm ' + has_edit + '" href="#" title="冻结" onclick="member.updateStatus(\''
                            //             + row.memberId
                            //             + '\')">冻结</a> ';
                            //
                            //     } else if (row.status == '1') {
                            //         c = '<a class="btn btn-info btn-sm ' + has_edit + '" href="#" title="解冻" onclick="member.updateStatus(\''
                            //             + row.memberId
                            //             + '\')">解冻</a> ';
                            //     }
                            //     e = '<a class="btn btn-danger btn-sm ' + has_edit + '" href="#" title="结束充电" onclick="member.updateChargeStatus(\''
                            //         + row.memberId
                            //         + '\')">结束充电</a> ';
                            // }
                            // if (row.chargeStatus == '1') {
                            //     return d + b + a + e + f;
                            // } else {
                            //     return d + b + a + c + f;
                            // }
                            return d;


                        }
                    }
                ]/*, onLoadSuccess: function () {
                    initSwitch();
                }, onPageChange: function () {
                    initSwitch();
                }*/
            });
    };

    function status_switch(value, row, index) {
        if (value == '0') {
            return '<input class="tgl tgl-skewed" onclick="member.onSwitchChange(' + row.memberId + ',1 )" id="cb' + row.memberId + '" type="checkbox">' +
                '<label class="tgl-btn" data-tg-off="启动" data-tg-on="禁用" for="cb' + row.memberId + '"></label>'
        } else {
            return '<input class="tgl tgl-skeweds"  onclick="member.onSwitchChange(' + row.memberId + ',0 )" id="cb' + row.memberId + '" type="checkbox">' +
                '<label class="tgl-btn isok" data-tg-off="禁用" data-tg-on="启动" for="cb' + row.memberId + '"></label>'
        }
    }

    function onSwitchChange(isId, state) {
        //修改操作
        $.ajax({
            type: "post",
            dataType: "json",
            async: false,
            url: prefix + "/updateMemberStatus",
            data: {
                status: state,
                id: isId
            },
            success: function (data) {
                reLoad();
            },
            error: function (xhr, error, exception) {
                let errorMsg = xhr.responseText;
                openMsg("error", "系统异常，" + errorMsg + "，请联系管理员！");
            }
        });
    }

    /*function initSwitch() {
        $("[name='member-status']").bootstrapSwitch({
            onText: "启用",      // 设置ON文本
            offText: "禁用",    // 设置OFF文本
            onColor: "primary",// 设置ON文本颜色(info/success/warning/danger/primary)
            offColor: "warning",  // 设置OFF文本颜色 (info/success/warning/danger/primary)
            size: "mini",    // 设置控件大小,从小到大  (mini/small/normal/large)
            hadleWidth: "20",
            // 当开关状态改变时触发
            onSwitchChange: function (event, status) {
                //修改操作
                $.ajax({
                    type: "post",
                    dataType: "json",
                    async: false,
                    url: prefix + "/updateMemberStatus",
                    data: {
                        status: status ? 0 : 1,
                        id: this.value
                    },
                    success: function (data) {
                        $('#TestTables').bootstrapTable('refresh'); //Table页面刷新
                    },
                    error: function (xhr, error, exception) {
                    }
                });
            }
        })
    }*/

    function updateChargeStatus(memberId) {
        layer.confirm('确定要变更状态？', {
            btn: ['确定', '取消']
        }, function (index) {
            $.ajax({
                url: prefix + "/updateChargeStatus",
                type: "post",
                data: {
                    'memberId': memberId
                },
                success: function (data) {
                    layer.close(index);
                    if (data.status == 200) {
                        layer.msg("变更成功");
                        reLoad();
                    } else {
                        layer.msg(data.message);
                    }
                }
            });
        })
    }

    function integralAccountRecord(memberId) {
        location.href = premix + "/ugsMemberPointRecord/" + memberId;
    }

    function memberAccountRecord(memberId) {
        location.href = jsctx + "/memberAccount/memberAccountRecord/" + memberId;
    }

    function recharge(memberId) {
        location.href = jsctx + "/memberAccount/recharge/" + memberId;
    }

    function detailMember(memberId) {
        //缓存数据
        let mobile = $("#mobile").val();
        let nickname2 = $("#nickname2").val();
        var offset = $("#exampleTable").bootstrapTable("getOptions").pageNumber
        localStorage.setItem("memberPageCache", JSON.stringify({mobile: mobile, nickname2: nickname2, offset: offset}));

        location.href = prefix + "/detailMember/" + memberId;
    }

    function updateStatus(memberId) {
        layer.confirm('确定要变更状态？', {
            btn: ['确定', '取消']
        }, function (index) {
            $.ajax({
                url: prefix + "/updateStatus",
                type: "post",
                data: {
                    'memberId': memberId
                },
                success: function (data) {
                    layer.close(index);
                    if (data.status == 200) {
                        layer.msg("变更成功");
                        reLoad();
                    } else {
                        layer.msg(data.message);
                    }
                }
            });
        })
    }

    function exportMemberInfo() {
        let selectRows = $("#exampleTable").bootstrapTable('getSelections');
        let memberIdList = new Array();
        for (let i = 0; i < selectRows.length; i++) {
            memberIdList.push(selectRows[i].memberId)
        }

        $.fileDownload(prefix + "/exportMemberInfo", { // 后台请求链接
            httpMethod: "get",　　　　　　　　// 请求方式
            contentType: 'application/json',　 // 请求头
            data: {　　　　　　　　　　　　　　　// 参数，左边为后台接收的参数名，右边为前端获取的值，
                mobile: $("#mobile").val().trim(),
                // memberType: $("#memberType").val().trim(),
                // status: $("#status").val().trim(),
                // chargeStatus: $("#chargeStatus").val().trim(),
                nickname: $("#nickname2").val().trim(),
                selectRows: JSON.stringify(memberIdList),
                // remark: $("#remark").val().trim(),
                // startTime: $("#startTime").val().trim(),
                // endTime: $("#endTime").val().trim(),
                // count: $("#count").val().trim() == '' ? 0 : $("#count").val().trim(),
                offset: $('.active .page-link').text(),
                limit: $(".page-size").text()
            },
            prepareCallback: function (url) {
                layer.msg("文件下载中...", {time: -1})
            },
            abortCallback: function (url) {
                // 异常终止
                layer.msg("文件下载异常！！");
            },
            successCallback: function (url) {
                layer.msg("文件下载成功！！", {time: 1500});
            },
            failCallback: function (data) {
                var str = "{" + data.substring(data.indexOf("{") + 1, data.indexOf("}")) + "}";
                layer.msg(JSON.parse(str).message);
            }
        })
    }

    return {
        init: init,
        reLoad: reLoad,
        getCheckedRoles: getCheckedRoles,
        memberAccountRecord: memberAccountRecord,
        recharge: recharge,
        updateStatus: updateStatus,
        detailMember: detailMember,
        exportMemberInfo: exportMemberInfo,
        updateChargeStatus: updateChargeStatus,
        onSwitchChange: onSwitchChange,
        integralAccountRecord: integralAccountRecord
    };
})();


var saveMemberRemark = (function () {
    function init() {
        validateRule();
    };


    var isajaxsend = true;

    function save() {
        if (isajaxsend) {
            var formData = new FormData($("#frmMember")[0]);
            $("#roleIds").val(getCheckedRoles());
            $.ajax({
                cache: true,
                type: "POST",
                url: prefix + "/saveMemberRemark",
                data: formData,
                processData: false,
                contentType: false,
                async: false,
                beforeSend: function () {
                    isajaxsend = false
                },
                error: function (request) {
                    parent.layer.alert("Connection error");
                },
                success: function (data) {
                    if (data.status == 200) {
                        parent.layer.msg("操作成功");
                        window.history.back();
                    } else {
                        parent.layer.alert(data.message)
                    }

                },
                complete: function () {
                    isajaxsend = false
                }
            });
        }
    }

    function validateRule() {
        var icon = "<i class='fa fa-times-circle'></i> ";
        $("#frmMember").validate({
            rules: {},
            messages: {},
            submitHandler: function (form) {
                save();
            }
        })
    }

    return {
        init: init
    };


})();
